package net.ftzcode.util

import org.springframework.beans.factory.DisposableBean
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
import org.springframework.context.annotation.Lazy
import org.springframework.stereotype.Service

/**
 * Created by WangZiHe on 2017年9月26日
 * QQ/WeChat:648830605
 * QQ-Group:368512253
 * Blog:www.520code.net
 * Github:https://github.com/yancheng199287
 */


@Lazy(false)
@Service
object SpringUtils : ApplicationContextAware, DisposableBean {

    private var applicationContext: ApplicationContext? = null

    override fun setApplicationContext(applicationContext: ApplicationContext) {
        SpringUtils.applicationContext = applicationContext
    }

    fun <T> getBean(beanName: String): T {
        isInjected()
        return applicationContext!!.getBean(beanName) as T
    }

    fun <T> getBean(requiredType: Class<T>): T {
        isInjected()
        return applicationContext!!.getBean(requiredType)
    }

    private fun isInjected() {
        if (SpringUtils.applicationContext == null) {
            throw  RuntimeException("springUtils applicationContext is not injected!")
        }
    }

    override fun destroy() {
        SpringUtils.applicationContext = null
    }


}
